home *** CD-ROM | disk | FTP | other *** search
/ Experimental BBS Explossion 3 / Experimental BBS Explossion III.iso / c / cujoct93.zip / 1110059A < prev    next >
Text File  |  1993-07-14  |  2KB  |  84 lines

  1. // This is a partial listing of
  2. // the base class for SPList,
  3. // it handles the underlying dynamic
  4. // array mechanism
  5. template<class T>
  6. class SPListBase
  7. {
  8. private:
  9.   enum{ALLOCINC=20}; // default array size
  10.   T *a;            // the actual data
  11.   int cnt;    // the number of elements in the array
  12.   int first;    // the start of the array
  13.   int allocated;// amount allocated for the array
  14.   int allocinc; // amount to re-allocate to array
  15.  
  16.   void grow(int amnt= 0, int newcnt= -1); // make array grow
  17.  
  18. protected:
  19.   void compact(const int i); // remove an element from the array
  20.  
  21. public:
  22.   SPListBase(int n= ALLOCINC) // default constructor
  23.   {
  24.     a= new T[n];
  25.     cnt= 0;
  26.     first= n>>1; // start off in the middle
  27.     allocated= n;
  28.     allocinc= n;
  29.   }
  30.  
  31.   // copy constructor
  32.   SPListBase(const SPListBase<T>& n);
  33.  
  34.   // assignment operator
  35.   SPListBase<T>& SPListBase<T>::operator=(const SPListBase<T>& n);
  36.  
  37.   virtual ~SPListBase(){ // destuctor
  38.     delete [] a;
  39.   }
  40.  
  41.   // index operator
  42.   INLINE T& operator[](const int i);
  43.  
  44.   const T& operator[](const int i) const{
  45.     // generate an assert error if indices don't make sense
  46.     assert((i >= 0) && (i < cnt));
  47.     return a[first+i];
  48.   }
  49.  
  50.   int count(void) const{ return cnt; }
  51.  
  52.   // add an element to the end of the array
  53.   void add(const T& n){
  54.     if(cnt+first >= allocated) grow();
  55.     a[first+cnt]= n;
  56.     cnt++;
  57.   }
  58.   
  59.   // add an element into middle of array
  60.   void add(const int i, const T& n);
  61.  
  62.   // reset array
  63.   void erase(void){ cnt= 0; first= (allocated>>1);}
  64. };
  65.  
  66. // Allow the array to grow if index is out of range
  67. template <class T>
  68. INLINE T& SPListBase<T>::operator[](const int i)
  69. {
  70.   assert((i >= 0) && (first >= 0) && ((first+cnt) <= allocated));
  71.   int indx= first+i;
  72.     
  73.   if(indx >= allocated){  // need to grow it
  74.     // index as yet unused element
  75.     grow((indx-allocated)+allocinc, i+1); 
  76.     indx= first+i; // first will have changed in grow()
  77.   }
  78.   assert(indx >= 0 && indx < allocated);
  79.  
  80.   if(i >= cnt) cnt= i+1;  // it grew
  81.   return a[indx];
  82. }
  83.  
  84.